package org.example.erat.model.export;

import com.opencsv.CSVWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class CsvExportStrategy implements ExportStrategy {
    @Override
    public void exportStatistics(File directory, Map<String, List<String>> studentStats,
                                 Map<String, List<String>> experimentStats) throws IOException {
        // 导出学生统计
        exportToCsv(new File(directory, "学生统计.csv"), studentStats, new String[]{"学号", "缺交次数", "缺交实验列表"});

        // 导出实验统计
        exportToCsv(new File(directory, "实验统计.csv"), experimentStats, new String[]{"实验编号", "缺交人数", "缺交学生列表"});
    }

    private void exportToCsv(File file, Map<String, List<String>> stats, String[] headers) throws IOException {
        try (CSVWriter writer = new CSVWriter(new FileWriter(file))) {
            // 写入表头
            writer.writeNext(headers);

            // 写入数据
            for (Map.Entry<String, List<String>> entry : stats.entrySet()) {
                String[] row = new String[3];
                row[0] = entry.getKey();
                row[1] = String.valueOf(entry.getValue().size());
                row[2] = String.join(", ", entry.getValue());
                writer.writeNext(row);
            }
        }
    }
}